/*
 * Copyright 2016 Alibaba Group Holding Limited
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */
#include "utils.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

int __property_debug = 0;
__attribute__((constructor)) static void check_debug_enabled() {
    char *enabled = getenv("PROPERTY_DEBUG");
    if (enabled == NULL) enabled = "";
    __property_debug = strcmp("true", enabled) ? 0 : 1;
    INFO("__property_debug %d", __property_debug);
}


static bool read_cmdline(int pid, char *cmdline, int len) {
    char path[64];
    snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
    int fd = open(path, O_RDONLY);
    if (fd < 0) {
        ERROR("failed to open %s: %d", path, errno);
        return false;
    }

    int n = read(fd, cmdline, len-1);
    if (n < 0) n = 0;

    /* get rid of trailing newline, it happens */
    if (n > 0 && cmdline[n-1] == '\n') n--;
    cmdline[n] = 0;
    close(fd);
    return true;
}

void log_property_failure(const char *key, const char *value) {
    int uid = getuid();
    int pid = getpid();
    char cmdline[1024];
    bool result = read_cmdline(pid, cmdline, sizeof(cmdline));
    if (!result) cmdline[0] = 0;
    ERROR("property operation failed, pid:%d uid:%u cmdline:`%s` prop:`%s`->`%s`", pid, uid, cmdline, key, value);
}
